<template>
  <div>
    <el-container>
      <el-header style="margin-top: 10px;height: auto;">
        <el-row>
          <el-input
            v-model="kwInput"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          </el-input>
          <el-button
            type="primary"
            class="el-icon-plus add-btn"
            @click="handleAction('create', '添加')"
          >添加
          </el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%"
          @sort-change="handleSort"
        >
          <el-table-column align="center" label="账号" prop="username" sortable="custom" />
          <el-table-column align="center" label="使用人" prop="user_name" sortable="custom">
            <template slot-scope="scope">
              <span>{{ scope.row.user_name || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="日限" prop="daily_limit" sortable="custom" />
          <el-table-column align="center" label="小时限额" prop="hourly_limit" sortable="custom" />
          <el-table-column align="center" label="可发邮件" prop="sendable" sortable="custom">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.sendable"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" width="200">
            <template slot-scope="scope">
              <div>
                <el-button size="mini" type="success" @click="handleAction('edit', scope.row)">修改</el-button>
              </div>
              <div style="margin-top: 5px;">
                <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item v-if="action !== 'delete'" label="邮箱平台" prop="platform">
          <el-select v-model="temp.platform" placeholder="请选择" @change="handleChantType">
            <el-option
              v-for="item in platforms"
              :key="item.value"
              :label="item.label"

              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="邮箱账号">
          <el-input v-model="temp.username" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="邮箱密码">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="邮箱使用人">
          <el-select v-model="temp.user" placeholder="请选择邮箱使用人" clearable filterable>
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="服务类型" prop="server_type">
          <el-select v-model="temp.server_type" placeholder="请选择" @change="handleChantType">
            <el-option
              v-for="item in server_types"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="server">
          <el-input v-model="temp.server" />
        </el-form-item>

        <el-form-item v-if="action !== 'delete'" label="port">
          <el-input v-model="temp.port" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="daily_limit">
          <el-input v-model="temp.daily_limit" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="hourly_limit">
          <el-input v-model="temp.hourly_limit" />
        </el-form-item>
        <el-form-item v-if="action !== 'delete'" label="可发邮件">
          <el-switch
            v-model="temp.sendable"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false; saveloading=false;">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" :loading="saveloading" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmmailserverconfig'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmmailserverconfig',
  data() {
    return {
      saveloading: false,
      data: [],
      listLoading: false,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      title: '',
      users: [], // 用户列表
      server_types: [
        {
          label: 'SMTP',
          value: 'SMTP'
        },
        {
          label: 'POP3',
          value: 'POP3'
        },
        {
          label: 'IMAP',
          value: 'IMAP'
        }
      ],
      platforms: [
        {
          label: 'Gmail',
          value: 'gmail'
        },
        {
          label: '网易邮箱',
          value: '163'
        },
        {
          label: '阿里云邮箱',
          value: 'aliyun'
        },
        {
          label: '腾讯企业邮箱',
          value: 'qq'
        },
        {
          label: 'Outlook',
          value: 'outlook'
        },
        {
          label: 'Yahoo Mail',
          value: 'yahoo'
        },
        {
          label: 'iCloud Mail',
          value: 'icloud'
        },
        {
          label: 'Zoho Mail',
          value: 'zoho'
        },
        {
          label: '新浪邮箱',
          value: 'sina'
        },
        {
          label: '搜狐邮箱',
          value: 'sohu'
        },
        {
          label: 'mailgun',
          value: 'mailgun'
        },
        {
          label: 'mailchimp',
          value: 'mailchimp'
        },
        {
          label: '其他',
          value: 'other'
        }
      ],
      temp: {
        platform: 'gmail', // 添加平台字段
        server: 'smtp.zoho.com',
        port: '993',
        server_type: 'SMTP', // 指定服务器类型为SMTP
        username: '', // 添加用户名字段
        password: '',
        user: null, // 邮箱使用人
        sendable: true, // 是否可以作为发送账号
        enable: true, // 是否启用
        daily_limit: 500, // 日限额
        hourly_limit: 50 // 每小时限额
      },
      width: '',
      projects: [],
      innerDialogVisible: false
    }
  },
  created() {
    this.getList()
    this.getUserList() // 获取用户列表
  },
  methods: {
    resetTemp() {
      this.temp = {
        platform: 'gmail', // 添加平台字段
        server: 'imap.gmail.com',
        port: '993',
        server_type: 'imap', // 指定服务器类型为SMTP
        username: '', // 添加用户名字段
        password: '',
        user: null, // 邮箱使用人
        sendable: true, // 是否可以作为发送账号
        enable: true, // 是否启用
        daily_limit: 500, // 日限额
        hourly_limit: 50 // 每小时限额
      }
    },
    // 获取用户列表
    getUserList() {
      GetUsers().then(response => {
        this.users = response.data
      }).catch(err => {
        console.log('获取用户列表失败:', err)
      })
    },
    handleChantType() {
      const serverMappings = {
        'SMTP': {
          'gmail': { server: 'smtp.gmail.com', port: '465' },
          '163': { server: 'smtp.163.com', port: '465' },
          'aliyun': { server: 'smtp.aliyun.com', port: '465' },
          'qq': { server: 'smtp.qq.com', port: '465' },
          'outlook': { server: 'smtp-mail.outlook.com', port: '587' }
          // 其他平台的SMTP配置
        },
        'IMAP': {
          'gmail': { server: 'imap.gmail.com', port: '993' },
          '163': { server: 'imap.163.com', port: '993' },
          'aliyun': { server: 'imap.aliyun.com', port: '993' },
          'qq': { server: 'imap.qq.com', port: '993' },
          'outlook': { server: 'imap-mail.outlook.com', port: '993' }
          // 其他平台的IMAP配置
        },
        'POP3': {
          'gmail': { server: 'pop.gmail.com', port: '995' },
          '163': { server: 'pop.163.com', port: '995' },
          'aliyun': { server: 'pop.aliyun.com', port: '995' },
          'qq': { server: 'pop.qq.com', port: '995' },
          'outlook': { server: 'pop-mail.outlook.com', port: '995' }
          // 其他平台的POP3配置
        }
      }
      const serverType = this.temp.server_type
      const platform = this.temp.platform
      if (serverMappings[serverType] && serverMappings[serverType][platform]) {
        const { server, port } = serverMappings[serverType][platform]
        this.temp.server = server
        this.temp.port = port
      } else {
        console.error('未知的服务器类型或平台')
        // 可以设置为默认值或提示用户手动输入
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      const title = row.username
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = row
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${title}?`
          // 复制
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${title}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        case 'create':
          if (!_data.username.length) {
            alert('必须填写邮箱账号')
            return
          }
          if (!_data.password.length) {
            alert('必须填写密码')
            return
          }
          if (!_data.server.length) {
            alert('必须填写smtp_host')
            return
          }
          this.saveloading = true
          Post(_data
          ).then(response => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('添加成功')
            this.saveloading = false
          })
          break
        case
          'delete'
          :
          this.saveloading = true
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
            this.saveloading = false
          })
          break
        case
          'edit'
          :
          this.saveloading = true
          Put(_data.id, _data).then((response) => {
            this.innerDialogVisible = false
            this.$emit('reload')
            this.getList()
            this.notify('更新成功')
            this.saveloading = false
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>
<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.top >>> .sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
